<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Route
 *
 * @author valentin
 */
class RM_JoomlaSEF_Router_Route_User implements RM_Controller_Router_Route_Interface {
    /**
     * Controller name
     *
     * @var string
     */
    protected $_controller = "";

    /**
     * Action name
     *
     * @var string
     */
    protected $_action = "";

    /**
     * Module name
     *
     * @var string
     */
    protected $_module = "";

    /**
     * @var string
     */
    protected $_alias = 'resmania';

    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        return new self($config->route, $defs);
    }

    /**
     * Prepares the route for mapping.
     *
     * @param string $route Map used to match with later submitted URL path
     * @param array $defaults Defaults for map variables with keys as variable names
     */
    public function __construct($defaults = array())
    {
        // get the alias name
        $joomlasefObj = new RM_JoomlaSEF;
        $settings = $joomlasefObj->getSettings()->toArray();
        $this->_alias = $settings[0]['aliasname'];

        $this->_controller = $defaults['controller'];
        $this->_action = $defaults['action'];
        $this->_module = $defaults['module'];
    }

    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param string $path Path used to match against this routing map
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        $trimURL = trim($path, '/');
        //replace all old params that could damage our sef url
        $sefURL = str_replace(array('act=', 'task=', '?', '&'), array('', '', '/', '/'), $trimURL);

        $chunks = explode('/', $sefURL);

        $index = 0;
        for ($index = 0; $index < 100; $index++){
            $currentValue = trim($chunks[$index]);
            unset($chunks[$index]);
            if (strpos($currentValue, $this->_alias) === 0) {
                if (isset($_REQUEST['act'])) {
                    $return['controller'] = $_REQUEST['act'];
                }
                if (isset($_REQUEST['task'])) {
                    $return['action'] = $_REQUEST['task'];
                }
                //This is the last one before our needed information
                $index++;
                break;
            }
        }

        if (isset($return['controller']) == false) {
            $return['controller'] = isset($chunks[$index]) ? $chunks[$index] : $this->_controller;
        }
        unset($chunks[$index]); $index++;

        if (isset($return['action']) == false) {
            $return['action'] = isset($chunks[$index]) ? $chunks[$index] : $this->_action;
        }
        unset($chunks[$index]); $index++;

        $return['module'] = $this->_module;

        $this->_controller = $return['controller'];
        $this->_action = $return['action'];

        $arrayKeys = array();
        foreach ($chunks as $chunk) {
            parse_str($chunk, $result);
            $arrayKeys = array_merge_recursive($arrayKeys, $result);
        }
        foreach ($arrayKeys as $key => $value) {
            $return[$key] = $value;
        }
        return $return;
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        $url = JURI::root(). $this->_alias . '/' . $data['act'].'/'.$data['task'];

        unset($data['act']);
        unset($data['task']);

        if (count($data) > 0) {
            $url .= '/'.http_build_query($data, '', '/');
        }

        return $url;
    }

    /**
     * Returns an js code of function that assembles a URL path
     *
     * @return string JS function named 'RM.Common.AssembleURL' for assemble
     */
    public function getAccembleURLJsCode()
    {
        return "RM.Common.AssembleURL = function(json){
            if (json.forcefrontend === true){
                var url = RM.RootURL+'index2.php/".$this->_alias."/'+json.controller+'/'+json.action;
            } else {
                var url = RM.RootURL+'".$this->_alias."/'+json.controller+'/'+json.action;
            }

            if (json.parameters) {
                for (var i = 0; i < json.parameters.length; i++){
                    url += '/' + json.parameters[i].name + '=' + json.parameters[i].value;
                }
            }
            return url;
        }";
    }
}